package delete;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.JOptionPane;

import utility.connections;

/**
 * Servlet implementation class Delete_subcat
 */
public class Delete_subcat extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Delete_subcat() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String cod=request.getParameter("txtCodice").toString().toLowerCase();
		String qry;
		try {
			Connection conn=connections.getConnection();
			Statement  st  =conn.createStatement();
			conn.setAutoCommit(false);
				qry="select count(*) from bene where sottocategoriabene='"+cod+"'";
				System.out.println(qry);
				ResultSet  xs=st.executeQuery(qry);
				String redirect="";
				if(xs.next())
				{
					if(xs.getInt(1)!=0)
					{
						System.out.println("RECORD PRESENTI");
						System.out.println(qry);
						redirect="ben/select_subcat.jsp?order=1&undel=1";
					}
					else 
					{
						qry="delete from bene where sottocategoriabene='"+cod+"'";
						System.out.println(qry);
						st.executeUpdate(qry);
						qry="delete from sottocategoriabene where codice='"+cod+"'";
						System.out.println(qry);
						st.executeUpdate(qry);
						redirect="ben/select_subcat.jsp?order=1";
					}
				}
			conn.commit();
			st.close();
			conn.close();
			
			if(request.getSession().getAttribute("type").toString().equalsIgnoreCase("1"))
				response.sendRedirect("adm/"+redirect);
			else
				response.sendRedirect("amm/"+redirect);
			
		} catch (SQLException e1) {
			System.out.println("e bo");
			e1.printStackTrace();
		} catch (ClassNotFoundException e1) {
			e1.printStackTrace();
		}
		
	}

}
